package org.budo.support.lang.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.springframework.util.Base64Utils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
public class Base64Util {
    public static String[] BASE64_PREFIXS = { "data:image/png;base64,", "data:image/jpeg;base64," };

    public static InputStream toInputStream(String base64) {
        if (StringUtil.isEmpty(base64)) {
            log.error("#17 toInputStream return null, base64=" + base64);
            return null;
        }

        try {
            byte[] bytes = decodeWithPrefix(base64);
            return new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            log.error("#20 base64=" + base64 + ", e=" + e, e);
            throw new RuntimeException(StringUtil.cutLeft(base64, 20), e);
        }
    }

    public static byte[] decodeWithPrefix(String base64) {
        for (String prefix : BASE64_PREFIXS) {
            if (base64.startsWith(prefix)) {
                String body = base64.substring(prefix.length());
                return Base64Utils.decodeFromString(body);
            }
        }

        return Base64Utils.decodeFromString(base64);
    }
}